package cardcreator;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class Preview extends JPanel implements ItemListener, CaretListener {
	private static final long serialVersionUID = -6884457752974891201L;
	
	private static final int PADDING=10;
	private static final int ROUNDING=20;
	private static final double RATIO=1.41;
	
	private static final Color BACKGROUND = new Color(3,46,0);
	private static final Color GROUPCOLOR = new Color(0,58,103);
	private static final Color ILLUMINATICOLOR = Color.BLACK;
	private static final Color ACTIONCOLOR = new Color(101,0,0);
	private static final Color TEXTCOLOR = Color.WHITE;
	
	private Color _cardcolor = Preview.GROUPCOLOR;
	private String _name = "";
	
	private int _width = 0;
	private int _height = 0;
	private int _x = 0;
	private int _y = 0;
	
	public Preview() {
		this.setBackground(Preview.BACKGROUND);
	}
	
	public void paintComponent(Graphics graphics) {
		super.paintComponent(graphics);
		Graphics2D g = (Graphics2D) graphics;
		
		setCardSize();
		drawCard(g);
		drawText(g);
		drawImage(g);
	}

	private void setCardSize() {
		_width = Math.min(this.getWidth()-Preview.PADDING*2,(int)((this.getHeight()-Preview.PADDING*2)/Preview.RATIO));
		_height = (int)(_width*Preview.RATIO);
		_x=(getWidth()-_width)/2;
		_y=(getHeight()-_height)/2;
	}

	private void drawCard(Graphics2D g) {		
		g.setColor(_cardcolor);
		g.fillRoundRect(_x,_y,_width,_height,Preview.ROUNDING,Preview.ROUNDING);
	}

	private void drawText(Graphics2D g) {
		g.setColor(TEXTCOLOR);
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));
		
		FontMetrics fm = g.getFontMetrics();
		Rectangle2D bounds = fm.getStringBounds(_name,g);
		g.drawString(_name,(int)(_x+(_width-bounds.getWidth())/2),(int)(_y+bounds.getHeight()+Preview.PADDING/2));
	}

	private void drawImage(Graphics2D g) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if ("Illuminati".equals(e.getItem()))
			_cardcolor = ILLUMINATICOLOR;
		else if ("Group".equals(e.getItem()))
			_cardcolor = GROUPCOLOR;
		else
			_cardcolor = ACTIONCOLOR;
		repaint();
	}

	@Override
	public void caretUpdate(CaretEvent e) {
		JTextField name=(JTextField)e.getSource();
		_name=name.getText();
		repaint();
	}
}
